﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 编号规则服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class NumberingrulesService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Numberingrules> _numberingrulesRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public NumberingrulesService(SqlSugarRepository<Numberingrules> numberingrulesRep, ISqlSugarClient sqlSugarClient)
    {
        _numberingrulesRep = numberingrulesRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询编号规则 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询编号规则")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<NumberingrulesOutput>> Page(PageNumberingrulesInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _numberingrulesRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u =>
                u.Forms.Contains(input.Keyword) ||
                u.Prefix.Contains(input.Keyword) ||
                u.TimeRules.Contains(input.Keyword) ||
                u.GenerateRules.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Forms), u => u.Forms.Contains(input.Forms.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Prefix), u => u.Prefix.Contains(input.Prefix.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TimeRules), u => u.TimeRules.Contains(input.TimeRules.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GenerateRules), u => u.GenerateRules.Contains(input.GenerateRules.Trim()))
            .WhereIF(input.Serialnumber != null, u => u.Serialnumber == input.Serialnumber)
            .WhereIF(input.Increments != null, u => u.Increments == input.Increments)
            .WhereIF(input.Operator != null, u => u.Operator == input.Operator)
            .WhereIF(input.OperatingTimeRange?.Length == 2, u =>
                u.OperatingTime >= input.OperatingTimeRange[0] &&
                u.OperatingTime <= input.OperatingTimeRange[1])
            // 修复参数名称：operator -> op
            .LeftJoin<UserInfo>((u, op) => u.Operator == op.Id)
            .Select((u, op) => new NumberingrulesOutput
            {
                Id = u.Id,
                Forms = u.Forms,
                Prefix = u.Prefix,
                TimeRules = u.TimeRules,
                Serialnumber = u.Serialnumber,
                Increments = u.Increments,
                GenerateRules = u.GenerateRules,
                Operator = u.Operator,
                // 处理op可能为null的情况
                OperatorFkDisplayName = op != null ? op.UserName : "",
                OperatingTime = u.OperatingTime,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });

        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取编号规则详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取编号规则详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Numberingrules> Detail([FromQuery] QueryByIdNumberingrulesInput input)
    {
        return await _numberingrulesRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加编号规则 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加编号规则")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddNumberingrulesInput input)
    {
        var entity = input.Adapt<Numberingrules>();
        return await _numberingrulesRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新编号规则 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新编号规则")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateNumberingrulesInput input)
    {
        var entity = input.Adapt<Numberingrules>();
        await _numberingrulesRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除编号规则 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除编号规则")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteNumberingrulesInput input)
    {
        var entity = await _numberingrulesRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _numberingrulesRep.FakeDeleteAsync(entity);   //假删除
        //await _numberingrulesRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除编号规则 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除编号规则")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteNumberingrulesInput> input)
    {
        var exp = Expressionable.Create<Numberingrules>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _numberingrulesRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _numberingrulesRep.FakeDeleteAsync(list);   //假删除
        //return await _numberingrulesRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataNumberingrulesInput input)
    {
        var operatorData = await _numberingrulesRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Numberingrules>(input.FromPage, (u, r) => u.Id == r.Operator)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "operator", operatorData },
        };
    }
    
    /// <summary>
    /// 导出编号规则记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出编号规则记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageNumberingrulesInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportNumberingrulesOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "编号规则导出记录");
    }
    
    /// <summary>
    /// 下载编号规则数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载编号规则数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportNumberingrulesOutput>(), "编号规则导入模板", (_, info) =>
        {
            if (nameof(ExportNumberingrulesOutput.OperatorFkDisplayName) == info.Name) return _numberingrulesRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入编号规则记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入编号规则记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportNumberingrulesInput, Numberingrules>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 操作人
                    var operatorLabelList = pageItems.Where(x => x.OperatorFkDisplayName != null).Select(x => x.OperatorFkDisplayName).Distinct().ToList();
                    if (operatorLabelList.Any()) {
                        var operatorLinkMap = _numberingrulesRep.Context.Queryable<UserInfo>().Where(u => operatorLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Operator = operatorLinkMap.GetValueOrDefault(e.OperatorFkDisplayName ?? "");
                            if (e.Operator == null) e.Error = "操作人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Numberingrules>>();
                    
                    var storageable = _numberingrulesRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Forms?.Length > 32, "目标表单长度不能超过32个字符")
                        .SplitError(it => it.Item.Prefix?.Length > 32, "编号前缀长度不能超过32个字符")
                        .SplitError(it => it.Item.TimeRules?.Length > 32, "时间规则长度不能超过32个字符")
                        .SplitError(it => it.Item.GenerateRules?.Length > 32, "编号生成规则长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
